﻿namespace SubSet
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.OleDb;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Reflection;

    public class Form1 : Form
    {
      //  List<Cell> w = new List<Cell>();
        private bool aborthere;
        private bool war1=false;
        private bool war2=false;
        private bool isOpenXMLFormat=true;
        private ToolStripMenuItem aboutToolStripMenuItem;
        private Button button1;
        private IContainer components;
        private DataGridView dataGridView1;
        private ToolStripMenuItem exitToolStripMenuItem;
        private ToolStripMenuItem fileToolStripMenuItem;
        private ToolStripMenuItem helpToolStripMenuItem;
        private Label label1;
        private Label label2;
        private Label label3;
        private int maxDecimals;
        private MenuStrip menuStrip1;
        private List<Cell> mySolution = new List<Cell>();
        private ToolStripMenuItem newToolStripMenuItem;
        private int noSolutions = -1;
        private ProgressBar progressBar1;
        private ToolStripMenuItem subSetSolutionByHarryCoyoteToolStripMenuItem;
        private double target;
        private double oldtarget;
        private TextBox textBox1;
        private TextBox textBox2;
        private double times;
        private ToolStripSeparator toolStripSeparator;
        private Button button2;
        private ToolStripMenuItem instructionsToolStripMenuItem;
        private PictureBox pictureBox2;
        private Label label4;
        private dzzControls.EffectsLabel effectsLabel1;
        private Timer timer1;
        private dzzControls.EffectsLabel effectsLabel2;
        private BackgroundWorker backgroundWorker1;
        private System.DirectoryServices.DirectorySearcher directorySearcher1;
        private FontDialog fontDialog1;
        private bool Lost = false;
        
        public Form1()
        {
            this.InitializeComponent();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
          //  w.Clear();
            war1=false;
            war2=false;
            this.button1.Visible = false;
            this.button2.Visible = true;
            this.aborthere = false;
            this.textBox2.Visible = true;
            this.textBox2.Text = "";
            this.label3.Visible = true;
            this.times = 0;
            this.maxDecimals = 0;
            this.target = oldtarget;
            int something = 0;
            
           // this.progressBar1.Visible = true;
           List<Cell> w = new List<Cell>();
           w.Clear();
           //if (this.dataGridView1.Columns.Count)
           

               this.noSolutions = -1;
               for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
               {
                   for (int m = 0; m < this.dataGridView1.Columns.Count; m++)
                   {
                       this.dataGridView1.Rows[i].Cells[m].Style.BackColor = Color.White;
                   }
               }
               int count = this.dataGridView1.Columns.Count;
               int num4 = this.dataGridView1.Rows.Count;
               for (int j = 0; j < count; j++)
               {
                   for (int n = 0; n < num4; n++)
                   {
                       double num7;
                       if (double.TryParse(this.dataGridView1.Rows[n].Cells[j].Value.ToString(), out num7) && (num7 != 0.0))
                       {
                           //   bool test = false;
                           if (!war1)
                           {
                               if (this.NumberDecimalPlaces(num7) > 3) { MessageBox.Show("A cell has a value with more than 3 decimal places. \r \n Truncating this value to 3 decimals places."); num7 = Math.Round(num7, 3); war1 = true; }
                           }
                           if (!war2)
                           {
                               if (Math.Abs(num7) > 999999) { MessageBox.Show("Warning! A cell has value > or < 999999. \r \n Results may be unpredictable."); war2 = true; }
                           }
                           // if (num7 < 999999) { MessageBox.Show("Warning! A cell has value < 999999. \r \n Results may exclude this value."); }

                           if (this.maxDecimals < this.NumberDecimalPlaces(num7))
                           {
                               this.maxDecimals = this.NumberDecimalPlaces(num7);
                           }
                           w.Add(new Cell(num7, n, j));
                           something++;
                       }
                   }

               }
               this.times = Math.Pow(10.0, (double)this.maxDecimals);
               for (int k = 0; k < w.Count; k++)
               {
                   w[k].contents *= this.times;
               }
               this.target *= this.times;
               if (something > 0)
               {
                   // this.button2.Visible = true;
                   backgroundWorker1.RunWorkerAsync(w);
               }
               else
               {
                   this.button1.Visible = true;
                   this.button2.Visible = false;
                   this.aborthere = true;
                   this.textBox2.Visible = false;
                   this.label3.Visible = false;
                   this.times = 0;
                   this.maxDecimals = 0;
                   this.target = oldtarget;
                   something = 0;
               }

           

           // this.button2.Visible = false;
        }

        public static double Combination(double n, double r)
        {
            double num = Math.Floor(r);
            double num2 = Math.Floor(n);
            if (((n < 1.0) || (r < 0.0)) || (((r > n) || (r != num)) || (n != num2)))
            {
                throw new Exception("Invalid Input to Combination Function: Number must be greater than Range");
            }
            return (Factorial(n) / (Factorial(r) * Factorial(n - r)));
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        public static double Factorial(double n)
        {
            if (n < 0.0)
            {
                throw new Exception("Cannot take the factorial of a negative number");
            }
            double num = 1.0;
            for (double i = 2.0; i < (n + 1.0); i++)
            {
                num *= i;
            }
            return num;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
           // SetStyle(ControlStyles.DoubleBuffer, true);
            this.textBox1.LostFocus += new EventHandler(this.textBox1_LostFocus);
            this.textBox1.GotFocus += new EventHandler(this.textBox1_GotFocus);
            this.AllowDrop = true;
            this.label4.Visible = false;
            base.DragEnter += new DragEventHandler(this.Panel1_DragEnter);
            base.DragDrop += new DragEventHandler(this.Panel1_DragDrop);
          //  this.label4.BackColor = Color.Transparent;
            this.effectsLabel1.BackColor = Color.Transparent;
            this.effectsLabel2.BackColor = Color.Transparent;
            Point poin = new Point();
            Point poin2 = new Point();
            poin.X = 10; poin.Y = 209;
            poin2.X = 772; poin2.Y = 209;
           // this.label4.Location = poin;
        //    this.effectsLabel1.Location = poin;
          //  this.effectsLabel1.Location = poin2;
           // this.label4.Parent = this.pictureBox2;
            this.effectsLabel1.Parent = this.pictureBox2;
            this.effectsLabel2.Parent = this.pictureBox2;
        }

        private string GetExcelColumnName(int columnNumber)
        {
            int num = columnNumber;
            string str = string.Empty;
            while (num > 0)
            {
                int num2 = (num - 1) % 0x1a;
                str = Convert.ToChar((int) (0x41 + num2)).ToString() + str;
                num = (num - num2) / 0x1a;
            }
            return str;
        }

        private string GetExcelSheetNames(string excelFile)
        {
            OleDbConnection connection = null;
            DataTable oleDbSchemaTable = null;
            //DataTable oleDbSchemaTable = null;
            string str2;
            string connectionString;
            try
            {  if (isOpenXMLFormat)  
        //read a 2007 file  
            {connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +  
            excelFile + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";  }
    else  
        //read a 97-2003 file  
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                    excelFile + ";Extended Properties=Excel 8.0;";
            }
              connection = new OleDbConnection(connectionString);
                connection.Open();
                oleDbSchemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (oleDbSchemaTable == null)
                {
                    return null;
                }
                string[] strArray = new string[oleDbSchemaTable.Rows.Count];
                int index = 0;
                foreach (DataRow row in oleDbSchemaTable.Rows)
                {
                    strArray[index] = row["TABLE_NAME"].ToString();
                    index++;
                }
                for (int i = 0; i < strArray.Length; i++)
                {
                }
                str2 = strArray[0];
            }
            catch (Exception)
            {
                str2 = null;
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                    connection.Dispose();
                }
                if (oleDbSchemaTable != null)
                {
                    oleDbSchemaTable.Dispose();
                }
            }
            return str2;
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.label1 = new System.Windows.Forms.Label();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.subSetSolutionByHarryCoyoteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.instructionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.label4 = new System.Windows.Forms.Label();
            this.effectsLabel1 = new dzzControls.EffectsLabel();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.effectsLabel2 = new dzzControls.EffectsLabel();
            this.directorySearcher1 = new System.DirectoryServices.DirectorySearcher();
            this.fontDialog1 = new System.Windows.Forms.FontDialog();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.menuStrip1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.BackColor = System.Drawing.SystemColors.ControlDark;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(83, 208);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(202, 37);
            this.label1.TabIndex = 0;
            this.label1.Text = "Processing...";
            this.label1.Click += new System.EventHandler(this.label1_Click);
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.AllowUserToResizeColumns = false;
            this.dataGridView1.AllowUserToResizeRows = false;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.ColumnHeadersVisible = false;
            this.dataGridView1.EnableHeadersVisualStyles = false;
            this.dataGridView1.Location = new System.Drawing.Point(27, 64);
            this.dataGridView1.MultiSelect = false;
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ReadOnly = true;
            this.dataGridView1.RowHeadersVisible = false;
            this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridView1.Size = new System.Drawing.Size(490, 244);
            this.dataGridView1.TabIndex = 1;
            this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(325, 36);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 2;
            this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            this.textBox1.Validating += new System.ComponentModel.CancelEventHandler(this.textBox1_Validating);
            this.textBox1.Validated += new System.EventHandler(this.textBox1_Validated);
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Maiandra GD", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(347, 14);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(60, 19);
            this.label2.TabIndex = 3;
            this.label2.Text = "Target";
            this.label2.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(442, 33);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 4;
            this.button1.Text = "Go";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem,
            this.helpToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(556, 24);
            this.menuStrip1.TabIndex = 5;
            this.menuStrip1.Text = "menuStrip1";
            this.menuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip1_ItemClicked);
            // 
            // fileToolStripMenuItem
            // 
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.newToolStripMenuItem,
            this.toolStripSeparator,
            this.exitToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
            this.fileToolStripMenuItem.Text = "&File";
            // 
            // newToolStripMenuItem
            // 
            this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.newToolStripMenuItem.Name = "newToolStripMenuItem";
            this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
            this.newToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
            this.newToolStripMenuItem.Text = "&New";
            this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
            // 
            // toolStripSeparator
            // 
            this.toolStripSeparator.Name = "toolStripSeparator";
            this.toolStripSeparator.Size = new System.Drawing.Size(138, 6);
            // 
            // exitToolStripMenuItem
            // 
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
            this.exitToolStripMenuItem.Text = "E&xit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            // 
            // helpToolStripMenuItem
            // 
            this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.aboutToolStripMenuItem,
            this.instructionsToolStripMenuItem});
            this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
            this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
            this.helpToolStripMenuItem.Text = "&Help";
            this.helpToolStripMenuItem.Click += new System.EventHandler(this.helpToolStripMenuItem_Click);
            // 
            // aboutToolStripMenuItem
            // 
            this.aboutToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.subSetSolutionByHarryCoyoteToolStripMenuItem});
            this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
            this.aboutToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.aboutToolStripMenuItem.Text = "&About...";
            this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
            // 
            // subSetSolutionByHarryCoyoteToolStripMenuItem
            // 
            this.subSetSolutionByHarryCoyoteToolStripMenuItem.Name = "subSetSolutionByHarryCoyoteToolStripMenuItem";
            this.subSetSolutionByHarryCoyoteToolStripMenuItem.Size = new System.Drawing.Size(187, 22);
            this.subSetSolutionByHarryCoyoteToolStripMenuItem.Text = "SubSet  Sum Solution";
            // 
            // instructionsToolStripMenuItem
            // 
            this.instructionsToolStripMenuItem.Name = "instructionsToolStripMenuItem";
            this.instructionsToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.instructionsToolStripMenuItem.Text = "Instructions";
            this.instructionsToolStripMenuItem.Click += new System.EventHandler(this.instructionsToolStripMenuItem_Click);
            // 
            // progressBar1
            // 
            this.progressBar1.Location = new System.Drawing.Point(27, 305);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(490, 23);
            this.progressBar1.TabIndex = 6;
            this.progressBar1.Visible = false;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(27, 35);
            this.textBox2.Name = "textBox2";
            this.textBox2.ReadOnly = true;
            this.textBox2.Size = new System.Drawing.Size(100, 20);
            this.textBox2.TabIndex = 7;
            this.textBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            this.textBox2.Visible = false;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(134, 37);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(50, 13);
            this.label3.TabIndex = 8;
            this.label3.Text = "Solutions";
            this.label3.Visible = false;
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(177, 120);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(173, 85);
            this.button2.TabIndex = 9;
            this.button2.Text = "ABORT";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Visible = false;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // backgroundWorker1
            // 
            this.backgroundWorker1.WorkerReportsProgress = true;
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
            this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted_1);
            // 
            // pictureBox2
            // 
            this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
            this.pictureBox2.Location = new System.Drawing.Point(27, 64);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(490, 303);
            this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
            this.pictureBox2.TabIndex = 11;
            this.pictureBox2.TabStop = false;
            this.pictureBox2.Click += new System.EventHandler(this.pictureBox2_Click);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.BackColor = System.Drawing.SystemColors.Control;
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 27.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Location = new System.Drawing.Point(38, 192);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(469, 42);
            this.label4.TabIndex = 12;
            this.label4.Text = "Drop xls Spreadsheet Here";
            // 
            // effectsLabel1
            // 
            this.effectsLabel1.BackColor = System.Drawing.Color.Transparent;
            this.effectsLabel1.Font = new System.Drawing.Font("Showcard Gothic", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.effectsLabel1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.effectsLabel1.Letterwise = false;
            this.effectsLabel1.Location = new System.Drawing.Point(-87, -6);
            this.effectsLabel1.MaxAlpha = ((byte)(192));
            this.effectsLabel1.MaxRotate = ((sbyte)(30));
            this.effectsLabel1.MinAlpha = ((byte)(128));
            this.effectsLabel1.MinRotate = ((sbyte)(-30));
            this.effectsLabel1.MinZoom = ((byte)(50));
            this.effectsLabel1.Name = "effectsLabel1";
            this.effectsLabel1.ShadowColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
            this.effectsLabel1.ShadowOffset = new System.Drawing.Point(3, -5);
            this.effectsLabel1.Size = new System.Drawing.Size(585, 407);
            this.effectsLabel1.TabIndex = 13;
            this.effectsLabel1.Text = "Drop Excel File Here!";
            this.effectsLabel1.Click += new System.EventHandler(this.effectsLabel1_Click);
            // 
            // timer1
            // 
            this.timer1.Enabled = true;
            this.timer1.Interval = 4;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // effectsLabel2
            // 
            this.effectsLabel2.Font = new System.Drawing.Font("Showcard Gothic", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.effectsLabel2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.effectsLabel2.Letterwise = false;
            this.effectsLabel2.Location = new System.Drawing.Point(516, -70);
            this.effectsLabel2.MaxAlpha = ((byte)(192));
            this.effectsLabel2.MaxRotate = ((sbyte)(30));
            this.effectsLabel2.MinAlpha = ((byte)(128));
            this.effectsLabel2.MinRotate = ((sbyte)(-30));
            this.effectsLabel2.MinZoom = ((byte)(50));
            this.effectsLabel2.Name = "effectsLabel2";
            this.effectsLabel2.ShadowColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
            this.effectsLabel2.ShadowOffset = new System.Drawing.Point(3, -5);
            this.effectsLabel2.Size = new System.Drawing.Size(585, 407);
            this.effectsLabel2.TabIndex = 14;
            this.effectsLabel2.Text = "Drop Excel File Here!";
            // 
            // directorySearcher1
            // 
            this.directorySearcher1.ClientTimeout = System.TimeSpan.Parse("-00:00:01");
            this.directorySearcher1.ServerPageTimeLimit = System.TimeSpan.Parse("-00:00:01");
            this.directorySearcher1.ServerTimeLimit = System.TimeSpan.Parse("-00:00:01");
            // 
            // fontDialog1
            // 
            this.fontDialog1.Apply += new System.EventHandler(this.fontDialog1_Apply);
            // 
            // Form1
            // 
            this.AllowDrop = true;
            this.ClientSize = new System.Drawing.Size(556, 379);
            this.Controls.Add(this.effectsLabel2);
            this.Controls.Add(this.effectsLabel1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.pictureBox2);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.menuStrip1);
            this.DoubleBuffered = true;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximumSize = new System.Drawing.Size(572, 417);
            this.MinimumSize = new System.Drawing.Size(572, 417);
            this.Name = "Form1";
            this.Text = "Subset Sum Solution";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        public bool IsDivisble(int x, int n)
        {
            return ((x % n) == 0);
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        private void mySubSet(int target, List<Cell> w)
        {
            double num2 = Combination((double) w.Count, 1.0);
           // this.progressBar1.Maximum = (int) num2;
           // this.progressBar1.Step = 1;
            double r = 0.0;
            w.Sort((Comparison<Cell>) ((p1, p2) => p1.contents.CompareTo(p2.contents)));
            int d = target;
            Cell[] cellArray = w.ToArray();
            int[] numArray = new int[cellArray.GetLength(0)];
            for (int i = 0; i < cellArray.GetLength(0); i++)
            {
                r += cellArray[i].contents;
            }
            if (r < d)
            {
                MessageBox.Show("There is no solution");
             //   this.progressBar1.Visible = false;
            }
            else
            {
                int count = 0;
                this.mySolution.Clear();
                this.subset(0.0, 0, r, cellArray, numArray, count, d, w, this.dataGridView1);
                Cell[] cellArray2 = this.mySolution.ToArray();
               // this.button2.Visible = false;
               
                MethodInvoker action3 = delegate
                { this.button2.Visible = false; };
                this.button2.BeginInvoke(action3);
 MessageBox.Show("Finished getting solutions");
                if (this.noSolutions == -1)
                {
                    MessageBox.Show("There are no solutions.");
                    this.progressBar1.Visible = false;
                }
                else
                {MessageBox.Show("No of Solutions Processed " + (this.noSolutions + 1).ToString());
                    CreateExcelDoc doc = new CreateExcelDoc(this.noSolutions);
                    //get max gridX
                    int maxgridX = Int32.MinValue;
                    for (int i = 0; i < cellArray.Length; i++)
                    {
                        int val = (int)cellArray[i].gridX;
                        if (val > maxgridX)
                            maxgridX = val;
                    }
                    //get min gridX

                    //get max gridY
                    int maxgridY = Int32.MinValue;
                    for (int i = 0; i < cellArray.Length; i++)
                    {
                        int val2 = (int)cellArray[i].gridY;
                        if (val2 > maxgridY)
                            maxgridY = val2;
                    }
                    //get minGridY
                    //set up array
                    double[,] data = new double[maxgridX + 1, maxgridY + 1];
                    for (int x = 0; x < cellArray.Length; x++)
                    {
                        data[cellArray[x].gridX, cellArray[x].gridY] = (cellArray[x].contents / this.times);

                    }
                    for (int j = 0; j < (this.noSolutions + 1); j++)
                    {
                        doc.selectSheet(j + 1);
                        doc.changeSheetName(j + 1, "Solution");
                        for (int k = 0; k < cellArray2.GetLength(0); k++)
                        {
                            string str2 = this.GetExcelColumnName(cellArray2[k].gridY + 1) + ((cellArray2[k].gridX + 1)).ToString();
                            if (cellArray2[k].contents == j)
                            {
                                doc.createHeaders(cellArray2[k].gridX + 1, cellArray2[k].gridY + 1, "", str2, str2, 2, "YELLOW", true, 10, "n");
                            }
                        }
                      //  DataTable experiment = new DataTable();
                      //  for (int m = 0; m < cellArray.GetLength(0); m++)
                        {
                       //     doc.addData(cellArray[m].gridX + 1, cellArray[m].gridY + 1, (cellArray[m].contents / this.times).ToString(), "A1", "A1", "#.##0");
                          //  doc.RenderDataTableOnXlSheet(dataTable);
                        }
                     
                 
                        doc.differentaddData(data, maxgridX+1, maxgridY+1);
                    }
             //       this.progressBar1.Visible = false;
                }
            }
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = null;
            //this.label4.Visible=true;
            this.effectsLabel1.Visible = true;
            this.effectsLabel2.Visible = true;
            this.pictureBox2.Visible = true;
            this.label4.BackColor = Color.Transparent;
            this.effectsLabel2.BackColor = Color.Transparent;
            this.effectsLabel1.BackColor = Color.Transparent;
            Point poin = new Point();
            Point poin2 = new Point();
            poin.X = 10; poin.Y = 5;
            poin2.X = 572; poin2.Y = 5;
            this.label4.Location =  poin;
            this.effectsLabel1.Location = poin;
            this.effectsLabel2.Location = poin2;
this.label4.Parent = this.pictureBox2;
this.effectsLabel1.Parent = this.pictureBox2;
this.effectsLabel2.Parent = this.pictureBox2;
            this.button1.Visible = true;
            this.backgroundWorker1.CancelAsync();
            
        }
        private void textBox1_LostFocus(object sender, EventArgs e)
        {
          //  MessageBox.Show("lost fcus");
            Lost = true;
            // if (Lost == false)
            {
                double num;
                string text = "Not a valid target";
                if (!double.TryParse(this.textBox1.Text.ToString(), out num))
                {
                   // e.Cancel = true;
                    this.textBox1.Select(0, this.textBox1.Text.Length);
                    MessageBox.Show(text);
                }
                else
                {
                    this.target = num;
                    this.maxDecimals = this.NumberDecimalPlaces(this.target);
                }
                oldtarget = target;
            }
           // if (Form1..Focused)
              //  return;
            // Update the other text boxes here
        }

        private void textBox1_GotFocus(object sender, EventArgs e)
        {
           // MessageBox.Show("got fcus");
            Lost = false;

            //if (Form1. .Focused)
            //  return;
            // Update the other text boxes here
        }

        private int NumberDecimalPlaces(double dec)
        {
            string s = double.Parse(Convert.ToString(dec)).ToString();
            int num = s.IndexOf(".") + 1;
            int num2 = s.Length - num;
            int result = 0;
            if (int.TryParse(s, out result))
            {
                num2 = 0;
            }
            return num2;
        }

        private void Panel1_DragDrop(object sender, DragEventArgs e)
        {
            string[] data = (string[]) e.Data.GetData(DataFormats.FileDrop, false);
            foreach (string str in data)
            {
                new FileInfo(str);
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                dictionary["Provider"] = "Microsoft.Jet.OLEDB.4.0";
                dictionary["Data Source"] = str;
                dictionary["Extended Properties"] = "Excel 8.0;HDR=No;IMEX=1;\"";
              //  string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"";
                string connectionString;
            
              if (isOpenXMLFormat)  
        //read a 2007 file  
            {connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +  
            str + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";  }
    else  
        //read a 97-2003 file  
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                    str + ";Extended Properties=Excel 8.0;";
            }
                
                StringBuilder builder = new StringBuilder();
                foreach (KeyValuePair<string, string> pair in dictionary)
                {
                    builder.Append(pair.Key);
                    builder.Append('=');
                    builder.Append(pair.Value);
                    builder.Append(';');
                }
                this.pictureBox2.Visible = false;
                this.label4.Visible = false;
                this.effectsLabel1.Visible = false;
                builder.ToString();
                string str3 = "*";
                string excelSheetNames = this.GetExcelSheetNames(str);
                DataTable dataTable = new DataTable("fred");
                using (OleDbConnection connection = new OleDbConnection(connectionString))
                {
                    connection.Open();
                    DataSet set = new DataSet();
                    string str5 = string.Join<char>(",", str3.ToArray<char>());
                    using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT " + str5 + " FROM [" + excelSheetNames + "]", connection))
                    {
                        adapter.Fill(dataTable);
                        set.Tables.Add(dataTable);
                    }
                }
                BindingSource source = new BindingSource {
                    DataSource = dataTable
                };
                this.dataGridView1.DataSource = source;
                this.label1.Visible = false;
            }
        }

        private void Panel1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {
        }

        public void subset(double cs, int k, double r, Cell[] w1, int[] x1, int count, int d, List<Cell> w, DataGridView dataGridView1)
        {
            if (!this.aborthere)
            {
              //  MethodInvoker action = delegate
               // { textBox2.Text = (this.noSolutions + 1).ToString(); };
               //  textBox2.BeginInvoke(action);
             
                new List<Cell>();
                x1[k] = 1;
                if ((cs + w1[k].contents) == d)
                {
                    count++;
                    this.noSolutions++;
                    //this.backgroundWorker1.
                    System.Threading.Thread.Sleep(1);
                   backgroundWorker1.ReportProgress(this.noSolutions);
                    if (this.noSolutions == 0x3e8)
                    {
                        MessageBox.Show("There are more than 1000 solutions - This is going to take a while...");
                    }
                //    if ((this.IsDivisble(this.noSolutions, 0x3e8) && (this.noSolutions != 0x3e8)) && (this.noSolutions != 0))
                //    {
                //        Form2 form = new Form2(this.noSolutions);
                   //     form.ShowDialog();
                    //    if (form.abort)
                      //  {
                        //    this.aborthere = true;
                       // }
                  //  }
                  //n  MethodInvoker action2 = delegate
                  //n  { textBox2.Text = (this.noSolutions + 1).ToString(); };
                   //n textBox2.BeginInvoke(action2);
                  //  this.textBox2.Text = (this.noSolutions + 1).ToString();
                    for (int i = 0; i <= k; i++)
                    {
                        if (x1[i] == 1)
                        {
                            if (this.noSolutions == 0)
                            {
                                dataGridView1.Rows[w1[i].gridX].Cells[w1[i].gridY].Style.BackColor = Color.Aqua;
                            }
                            this.mySolution.Add(new Cell((double) this.noSolutions, w1[i].gridX, w1[i].gridY));
                        }
                    }
                }
                else if (((cs + w1[k].contents) + w1[k + 1].contents) <= d)
                {
                   // this.progressBar1.PerformStep();
                    this.subset(cs + w1[k].contents, k + 1, r - w1[k].contents, w1, x1, count, d, w, dataGridView1);
                }
                if ((((cs + r) - w1[k].contents) >= d) && ((cs + w1[k + 1].contents) <= d))
                {
                    x1[k] = 0;
                    this.subset(cs, k + 1, r - w1[k].contents, w1, x1, count, d, w, dataGridView1);
                }
            }
             // MethodInvoker action = delegate
            // { textBox2.Text = (this.noSolutions + 1).ToString(); };
            // textBox2.BeginInvoke(action);
            //this.button2.Visible = false;
            
        }

        private void textBox1_Validated(object sender, EventArgs e)
        {
        }

        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
           // if (Lost == false)
           // {
             //   double num;
               // string text = "Not a valid target";
              //  if (!double.TryParse(this.textBox1.Text.ToString(), out num))
               // {
                 //   e.Cancel = true;
                  //  this.textBox1.Select(0, this.textBox1.Text.Length);
                  //  MessageBox.Show(text);
               // }
               // else
               // {
                 //   this.target = num;
                   // this.maxDecimals = this.NumberDecimalPlaces(this.target);
               // }
               // oldtarget = target;
            //}
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.aborthere=true;
            this.button2.Visible = false;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List<Cell> w = (List<Cell>)e.Argument;
            this.mySubSet((int)this.target, w);
            MethodInvoker action3 = delegate
            { this.button2.Visible = false; };
            this.button2.BeginInvoke(action3);
           // this.button2.Visible = false;
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                 MessageBox.Show("Canceled!");
            }

            else if (!(e.Error == null))
            {
                MessageBox.Show ("Error: " + e.Error.Message);
            }

            else
            {
                MessageBox.Show ("Done!");
            }
        }

        private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                MessageBox.Show("Canceled!");
            }

            else if (!(e.Error == null))
            {
                MessageBox.Show("Error: " + e.Error.Message);
            }

            else
            {
                MessageBox.Show("Done!");
                this.button1.Visible = true;
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int count = e.ProgressPercentage + 1;
            textBox2.Text = string.Format("{0}", count);
        //  this.textBox2.Text = e.ProgressPercentage.ToString();
            //e.ProgressPercentage
        }

        private void instructionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This application helps you find which numbers from a list add to a target number. \r \n Drag an Excel spreadsheet (xls or xlsx) containing cells with numbers onto the application. \r \n N.B.  Make sure they are in 'Sheet1'. \r \n The program works with integers, decimals to 3 places and negatives. \r \n Set the target number and press go. \r \n Results will be output to a new workbook with the solutions appearing in separate sheets. (See the tabs at the bottom.)");
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
        private void RenderDataTableOnXlSheet(DataTable dt, Microsoft.Office.Interop.Excel.Worksheet xlWk, string[] columnNames, string[] fieldNames)
        {
            Microsoft.Office.Interop.Excel.Range rngExcel = null;
            Microsoft.Office.Interop.Excel.Range headerRange = null;

            try
            {
                // render the column names (e.g. headers)
                for (int i = 0; i < columnNames.Length; i++)
                    xlWk.Cells[1, i + 1] = columnNames[i];

                // for each column, create an array and set the array 
                // to the excel range for that column.
                for (int i = 0; i < fieldNames.Length; i++)
                {
                    string[,] clnDataString = new string[dt.Rows.Count, 1];
                    int[,] clnDataInt = new int[dt.Rows.Count, 1];
                    double[,] clnDataDouble = new double[dt.Rows.Count, 1];

                    string columnLetter = char.ConvertFromUtf32("A".ToCharArray()[0] + i);
                    rngExcel = xlWk.get_Range(columnLetter + "2", Missing.Value);
                    rngExcel = rngExcel.get_Resize(dt.Rows.Count, 1);

                    string dataTypeName = dt.Columns[fieldNames[i]].DataType.Name;

                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (fieldNames[i].Length > 0)
                        {
                            switch (dataTypeName)
                            {
                                case "Int32":
                                    clnDataInt[j, 0] = Convert.ToInt32(dt.Rows[j][fieldNames[i]]);
                                    break;
                                case "Double":
                                    clnDataDouble[j, 0] = Convert.ToDouble(dt.Rows[j][fieldNames[i]]);
                                    break;
                                case "DateTime":
                                    if (fieldNames[i].ToLower().Contains("time"))
                                        clnDataString[j, 0] = Convert.ToDateTime(dt.Rows[j][fieldNames[i]]).ToShortTimeString();
                                    else if (fieldNames[i].ToLower().Contains("date"))
                                        clnDataString[j, 0] = Convert.ToDateTime(dt.Rows[j][fieldNames[i]]).ToShortDateString();
                                    else
                                        clnDataString[j, 0] = Convert.ToDateTime(dt.Rows[j][fieldNames[i]]).ToString();

                                    break;
                                default:
                                    clnDataString[j, 0] = dt.Rows[j][fieldNames[i]].ToString();
                                    break;
                            }
                        }
                        else
                            clnDataString[j, 0] = string.Empty;
                    }

                    // set values in the sheet wholesale.
                    if (dataTypeName == "Int32")
                        rngExcel.set_Value(Missing.Value, clnDataInt);
                    else if (dataTypeName == "Double")
                        rngExcel.set_Value(Missing.Value, clnDataDouble);
                    else
                        rngExcel.set_Value(Missing.Value, clnDataString);
                }


                // figure out the letter of the last column (supports 1 letter column names)
                string lastColumn = char.ConvertFromUtf32("A".ToCharArray()[0] + columnNames.Length - 1);

                // make the header range bold
                headerRange = xlWk.get_Range("A1", lastColumn + "1");
                headerRange.Font.Bold = true;

                // autofit for better view
                xlWk.Columns.AutoFit();

            }
            finally
            {
                ReleaseObject(headerRange);
                ReleaseObject(rngExcel);
            }
        }

        private void ReleaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000; //WS_EX_COMPOSITED
                return cp;
            }
        }
        private void effectsLabel1_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            effectsLabel1.Left -= 2;
            if (effectsLabel1.Left + effectsLabel1.Width < 0)
                effectsLabel1.Left = this.ClientSize.Width;

            effectsLabel2.Left -= 2;
            if (effectsLabel2.Left + effectsLabel2.Width < 0)
                effectsLabel2.Left = this.ClientSize.Width;

        }

        private void fontDialog1_Apply(object sender, EventArgs e)
        {

        }

    }
}

